<?php
session_start();

// 验证用户是否登录
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

require_once 'track_online.php';

// 二维码扫描处理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // 检查上传文件
    if ($file['error'] !== UPLOAD_ERR_OK) {
        http_response_code(400);
        echo "上传失败，请重试。";
        exit();
    }

    $tempPath = $file['tmp_name'];
    $result = null;
    
    // 尝试本地扫描 (phpqrcode)
    require_once 'phpqrcode/qrlib.php';
    require_once 'phpqrcode/qrreader.php'; // 确保包含二维码解码库
    
    try {
        $qrcode = new QrReader($tempPath);
        $result = $qrcode->text();
        
        if (empty($result)) {
            throw new Exception("本地扫描失败");
        }
    } catch (Exception $e) {
        // 本地扫描失败，尝试使用ZXing API
        $apiUrl = 'https://zxing.org/w/decode';
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => ['f' => curl_file_create($tempPath)],
            CURLOPT_HTTPHEADER => ['Content-Type: multipart/form-data'],
        ]);

        $response = curl_exec($curl);
        $error = curl_error($curl);
        curl_close($curl);

        if ($error) {
            http_response_code(500);
            echo "二维码解析失败，服务器错误。";
            exit();
        }

        if (preg_match('/<pre>(.*?)<\/pre>/s', $response, $matches)) {
            $result = trim($matches[1]);
        } else {
            http_response_code(500);
            echo "二维码解析失败。";
            exit();
        }
    }

    echo $result ? $result : "无法识别二维码";
    exit();
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>二维码扫描 - JIILCHAT</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }
        
        /* 顶部导航栏 */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: #ffffff;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            z-index: 100;
            border-bottom: 1px solid #e0e4e9;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: #000;
            font-size: 20px;
            margin-right: 15px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: #e4e6eb;
        }
        
        .navbar-title {
            font-size: 18px;
            font-weight: 600;
            flex-grow: 1;
            color: #333;
        }
        
        /* 主内容区 */
        .content {
            margin-top: 70px;
            padding: 20px;
        }
        
        /* 扫描卡片 */
        .scan-card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            margin-bottom: 25px;
            text-align: center;
        }
        
        .card-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 1px solid #f0f2f5;
            color: #333;
        }
        
        .camera-container {
            position: relative;
            width: 100%;
            height: 280px;
            border-radius: 15px;
            overflow: hidden;
            background: #e0e4e9;
            margin-bottom: 25px;
            border: 1px solid #ddd;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        #camera-view {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .camera-placeholder {
            color: #7f8c8d;
            font-size: 40px;
        }
        
        .scan-actions {
            display: flex;
            justify-content: center;
            gap: 15px;
        }
        
        .scan-btn {
            padding: 12px 24px;
            background: linear-gradient(135deg, #333, #000);
            color: white;
            text-align: center;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 500;
            text-decoration: none;
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .scan-btn:hover {
            background: linear-gradient(135deg, #222, #000);
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.4);
        }
        
        .scan-btn.secondary {
            background: #ffffff;
            color: #333;
            border: 1px solid #ddd;
        }
        
        .scan-btn.secondary:hover {
            background: #f8f9fa;
        }
        
        /* 扫描框指示器 */
        .scan-guide-box {
            position: absolute;
            top: 25%;
            left: 10%;
            width: 80%;
            height: 50%;
            border: 2px solid rgba(78, 204, 163, 0.8);
            box-shadow: 0 0 0 100vmax rgba(0,0,0,0.5);
            pointer-events: none;
            display: none; /* 默认隐藏 */
        }
        
        .scan-line {
            position: absolute;
            height: 2px;
            width: 100%;
            background: linear-gradient(90deg, transparent, #4ecca3, transparent);
            top: 0;
            left: 0;
            animation: scan 3s infinite ease-in-out;
        }
        
        @keyframes scan {
            0%, 100% { top: 0; }
            50% { top: 100%; }
        }
        
        /* 加载弹窗 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.85);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        
        .modal-overlay.active {
            opacity: 1;
            visibility: visible;
        }
        
        .modal-content {
            background: #ffffff;
            border-radius: 20px;
            padding: 40px;
            text-align: center;
            max-width: 400px;
            width: 90%;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        }
        
        .modal-icon {
            font-size: 48px;
            color: #333;
            margin-bottom: 25px;
        }
        
        .modal-title {
            font-size: 22px;
            font-weight: 600;
            margin-bottom: 15px;
            color: #333;
        }
        
        .modal-text {
            color: #7f8c8d;
            margin-bottom: 25px;
            line-height: 1.6;
        }
        
        .loader {
            width: 50px;
            height: 50px;
            border: 5px solid rgba(51, 51, 51, 0.1);
            border-radius: 50%;
            border-top: 5px solid #333;
            margin: 25px auto;
            animation: spin 1.5s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 响应式设计 */
        @media (max-width: 600px) {
            .scan-actions {
                flex-direction: column;
            }
            
            .scan-btn {
                width: 100%;
            }
        }
        
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <div class="navbar">
        <button class="back-btn" onclick="history.back()">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="navbar-title">二维码扫描</div>
    </div>
    
    <div class="content">
        <!-- 扫描卡片 -->
        <div class="scan-card">
            <div class="card-title">扫描二维码</div>
            
            <!-- 摄像头容器 -->
            <div class="camera-container">
                <div class="camera-placeholder">
                    <i class="fas fa-camera"></i>
                </div>
                <video id="camera-view" class="hidden" autoplay playsinline></video>
                <div class="scan-guide-box">
                    <div class="scan-line"></div>
                </div>
            </div>
            
            <p style="color: #7f8c8d; margin-bottom: 25px; font-size: 15px;">
                将二维码放入扫描框中，或上传二维码图片
            </p>
            
            <div class="scan-actions">
                <button id="camera-toggle" class="scan-btn">
                    <i class="fas fa-video"></i> 开启摄像头
                </button>
                <button id="upload-btn" class="scan-btn secondary">
                    <i class="fas fa-file-image"></i> 上传图片
                </button>
            </div>
        </div>
    </div>
    
    <!-- 文件输入框 (隐藏) -->
    <input type="file" id="file-input" accept="image/*" class="hidden">
    
    <!-- 加载弹窗 -->
    <div class="modal-overlay" id="loading-modal">
        <div class="modal-content">
            <div class="modal-icon">
                <i class="fas fa-qrcode"></i>
            </div>
            <div class="modal-title">正在扫描二维码</div>
            <div class="modal-text">请稍候，正在解析二维码内容...</div>
            <div class="loader"></div>
        </div>
    </div>
    
    <script>
        // DOM元素引用
        const cameraView = document.getElementById('camera-view');
        const cameraToggle = document.getElementById('camera-toggle');
        const uploadBtn = document.getElementById('upload-btn');
        const fileInput = document.getElementById('file-input');
        const cameraPlaceholder = document.querySelector('.camera-placeholder');
        const scanGuideBox = document.querySelector('.scan-guide-box');
        const loadingModal = document.getElementById('loading-modal');
        
        // 状态变量
        let videoStream = null;
        let cameraActive = false;
        let scanningActive = false;
        
        // 切换摄像头
        cameraToggle.addEventListener('click', async () => {
            if (cameraActive) {
                stopCamera();
                cameraToggle.innerHTML = '<i class="fas fa-video"></i> 开启摄像头';
            } else {
                try {
                    await startCamera();
                    cameraToggle.innerHTML = '<i class="fas fa-video"></i> 关闭摄像头';
                } catch (error) {
                    console.error("无法开启摄像头: ", error);
                    alert("无法访问摄像头：" + (error.message || "请检查摄像头权限"));
                }
            }
        });
        
        // 上传图片
        uploadBtn.addEventListener('click', () => {
            fileInput.click();
        });
        
        // 处理文件选择
        fileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    // 显示加载状态
                    showLoading("正在扫描图片中的二维码...");
                    
                    // 尝试解析二维码
                    setTimeout(() => {
                        processImage(e.target.result);
                    }, 1500);
                }
                
                reader.readAsDataURL(this.files[0]);
            }
        });
        
        // 启动摄像头
        async function startCamera() {
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                throw new Error("您的浏览器不支持摄像头功能");
            }
            
            videoStream = await navigator.mediaDevices.getUserMedia({ 
                video: { facingMode: "environment" } 
            });
            
            cameraView.srcObject = videoStream;
            cameraView.classList.remove('hidden');
            cameraPlaceholder.classList.add('hidden');
            scanGuideBox.style.display = 'block'; // 显示扫描框
            cameraActive = true;
            
            // 启动扫描
            startScanning();
        }
        
        // 停止摄像头
        function stopCamera() {
            if (videoStream) {
                videoStream.getTracks().forEach(track => track.stop());
                videoStream = null;
            }
            cameraView.classList.add('hidden');
            cameraPlaceholder.classList.remove('hidden');
            scanGuideBox.style.display = 'none'; // 隐藏扫描框
            cameraActive = false;
            scanningActive = false;
        }
        
        // 开始扫描
        function startScanning() {
            if (scanningActive) return;
            scanningActive = true;
            
            const canvas = document.createElement('canvas');
            const canvasCtx = canvas.getContext('2d');
            
            function scan() {
                if (!scanningActive) return;
                
                try {
                    canvas.width = cameraView.videoWidth;
                    canvas.height = cameraView.videoHeight;
                    
                    canvasCtx.drawImage(cameraView, 0, 0, canvas.width, canvas.height);
                    const imageData = canvasCtx.getImageData(0, 0, canvas.width, canvas.height);
                    const code = jsQR(imageData.data, imageData.width, imageData.height);
                    
                    if (code) {
                        showLoading("扫描成功，正在处理...");
                        setTimeout(() => {
                            redirectToCodeResult(code.data);
                        }, 1000);
                    } else {
                        setTimeout(scan, 300);
                    }
                } catch (e) {
                    console.error("扫描错误: ", e);
                    setTimeout(scan, 500);
                }
            }
            
            scan();
        }
        
        // 处理图片中的二维码
        function processImage(imageData) {
            const img = new Image();
            img.src = imageData;
            
            img.onload = () => {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0, img.width, img.height);
                
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                const code = jsQR(imageData.data, imageData.width, imageData.height);
                
                if (code) {
                    setTimeout(() => {
                        redirectToCodeResult(code.data);
                    }, 1000);
                } else {
                    showLoading("尝试使用本地服务解析...");
                    
                    // 调用PHP本地扫描
                    setTimeout(() => {
                        scanViaPHP(img.src);
                    }, 1500);
                }
            };
        }
        
        // 使用PHP本地扫描
        function scanViaPHP(imageSrc) {
            fetch(imageSrc)
                .then(res => res.blob())
                .then(blob => {
                    const formData = new FormData();
                    formData.append('file', blob);
                    
                    return fetch(window.location.href, {
                        method: 'POST',
                        body: formData
                    });
                })
                .then(response => response.text())
                .then(data => {
                    setTimeout(() => {
                        redirectToCodeResult(data);
                    }, 1000);
                })
                .catch(error => {
                    console.error('本地解析错误:', error);
                    setTimeout(() => {
                        hideLoading();
                        alert("无法解析二维码，请尝试其他方式");
                    }, 1000);
                });
        }
        
        // 重定向到扫描结果
        function redirectToCodeResult(data) {
            hideLoading();
            
            if (data.startsWith('http://') || data.startsWith('https://')) {
                window.location.href = `web.php?link=${encodeURIComponent(data)}`;
            } else {
                alert(`扫描结果：${data}`);
                stopCamera();
            }
        }
        
        // 显示加载动画
        function showLoading(message) {
            if (message) {
                document.querySelector('.modal-text').textContent = message;
            }
            loadingModal.classList.add('active');
        }
        
        // 隐藏加载动画
        function hideLoading() {
            loadingModal.classList.remove('active');
            document.querySelector('.modal-text').textContent = "请稍候，正在解析二维码内容...";
        }
        
        // 页面卸载时停止摄像头
        window.addEventListener('beforeunload', () => {
            stopCamera();
        });
        
        // 移动设备自动尝试启用摄像头
        window.addEventListener('load', () => {
            if (/Mobi|Android/i.test(navigator.userAgent)) {
                setTimeout(() => {
                    cameraToggle.click();
                }, 1000);
            }
        });
    </script>
</body>
</html>